﻿#region

using System;
using System.Globalization;

#endregion

namespace Jiubang.Wap.HttpModules {
    internal static class UserAuthorize{
        /// <summary>
        /// 2亿以上的ID作为直播室临时用户ID，直播室分配范围在一亿以内<br/>
        /// 3亿以上的ID作为全网分配临时Id。
        /// </summary>
        private const int MaxRegistedUserId = 300000000;

        private static readonly Random _random = new Random();

        /// <summary>
        /// 根据临时Sid解析出一个整形数字作为临时UserId<br/>
        /// 正确的UserId位于300000000：1459599999之间
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="tempId"></param>
        /// <param name="channelId"></param>
        /// <returns></returns>
        public static bool TryParseTempId(string sid, out int tempId, out int channelId){
            if (sid == null || sid.Length != 11){
                channelId = 0;
                tempId = 0;
                return false;
            }
            int temp;
            if (!int.TryParse(sid.Substring(0, 3), NumberStyles.HexNumber, null, out channelId)){
                tempId = 0;
                return false;
            }
            if (!int.TryParse(sid.Substring(3, 1), NumberStyles.HexNumber, null, out tempId))
                return false;
            if (!int.TryParse(sid.Substring(4, 7), NumberStyles.HexNumber, null, out temp))
                return false;
            tempId = tempId*100000000 + temp + MaxRegistedUserId;
            return true;
        }

        /// <summary>
        /// [0,2)位16进制数为频道Id<br/>
        /// [2,3)位16进制数位当前小时数取12的余。<br/>
        /// [3,9]位16进制数为分，秒，毫秒首位和1000内随机数组合而成。<br/>
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="channelId"></param>
        /// <returns></returns>
        public static string BuildTempSid(DateTime dt, int channelId){
            if (channelId <= 0) channelId = dt.Minute;
            int tempId = ((dt.Minute*100 + dt.Second)*10 + dt.Millisecond/100)*1000 + _random.Next(1000);
            return string.Format("{0:X3}{1:X1}{2:X7}", channelId, dt.Hour%12, tempId);
        }

        /// <summary>
        /// 根据UserID判断是否注册用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static bool IsRegisteredUser(int userId){
            return userId > 0 && userId < MaxRegistedUserId;
        }
    }
}